<?php


namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Jobs\NewsUrl;
use App\Models\Cookbook;
use App\Models\NewUrl as NewUrlModel;
use App\Models\NewUrl;
use App\Models\Product;
use Illuminate\Http\Request;

class LinkController extends BaseController
{
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $input = $request->input();
        $search = ['title' => '', 'status' => -1, 'start_at' => '', 'end_at' => ''];
        $list = NewUrlModel::apply($search, $input)->where('user_id', $this->getUserId())->orderBy("id", "desc")
            ->paginate(per_page());
        return $this->paginate($list);
    }

    public function store(Request $request) {
        $this->validate($request, [
            'type' => 'required|in:cookbook,product,zero',
            'entity_id' => 'required'
        ]);
        $input = $request->input();
        $user = $this->getUser();
        if (!$user->is_daren && !$user->is_temp_daren)
            return $this->failed('请开通达人权限');

        $count = NewUrlModel::where('user_id', $user->id)->where('date', date('Ymd'))->whereIn('status', [0, 1])->count();
        if ($count >= 10) {
            return $this->failed('一天只能转10次');
        }
        $id = $input['entity_id'];
        if ($input['type'] == 'cookbook') {
            $model = Cookbook::find($id);
            $product_tile = $model->title;
        } else if($input['type'] == 'product') {
            $model = Product::find($id);
            $product_tile = $model->title;
        } else {
            $product_tile = '0元领取视频号专享福利';
        }
        $data = [
            'title' => $product_tile,
            'entity_id' => $id,
            'user_id' => $user->id,
            'type' => $input['type'],
            'date' => date('Ymd'),
            'msg_id' => 0,
        ];
        $model = NewUrl::create($data);
        $insert_id = $model->id;

        $this->dispatch(new NewsUrl($input['type'], $input['entity_id'], $user->id, $insert_id));
        return $this->success([]);
    }

}

